#include "LockFile.h"

LockFile :: LockFile ( const char* nombre, bool sobreescribir ) {

	this->nombre = nombre;

	this->fl.l_type = F_WRLCK;
	this->fl.l_whence = SEEK_SET;
	this->fl.l_start = 0;
	this->fl.l_len = 0;
	this->fl.l_pid = getpid ();

	if (sobreescribir)
		this->fd = open ( this->nombre.c_str(), O_TRUNC | O_RDWR, 0777 );
	else
		this->fd = open ( this->nombre.c_str(), O_CREAT | O_RDWR, 0777 );
}

int LockFile :: tomarLock (tipo_lock tipo) {

	if (tipo == lock_escritura)
		this->fl.l_type = F_WRLCK;
	else if (tipo == lock_lectura)
		this->fl.l_type = F_RDLCK;
	else return -1;

	int resultado = fcntl ( this->fd,F_SETLKW,&(this->fl) );

	return resultado;
}

int LockFile :: liberarLock () {

	this->fl.l_type = F_UNLCK;
	int resultado = fcntl ( this->fd,F_SETLK,&(this->fl) );
	return resultado;
}

int LockFile :: append ( const char* buffer,int buffsize ) {

	int resultado = -1;

	if ( this->fd > 0) {
		lseek ( this->fd,0,SEEK_END );
		resultado = write ( this->fd,buffer,buffsize );
	}
	return resultado;
}

int LockFile :: escribir ( const char* buffer,int buffsize ) {

	int resultado = -1;

	if ( this->fd > 0)
		resultado = write ( this->fd,buffer,buffsize );

	return resultado;
}

int LockFile :: leer ( char* buffer,int buffsize ) {

	int resultado = -1;

	if ( this->fd > 0)
		resultado = read ( this->fd,buffer,buffsize );

	return resultado;
}

size_t LockFile :: seek ( size_t pos ) {
	size_t resultado = 0;

	if ( this->fd > 0)
		resultado = lseek ( this->fd,pos,SEEK_SET );

	return resultado;
}

size_t LockFile :: size () {
	size_t resultado = 0;

	if ( this->fd > 0)
		resultado = lseek ( this->fd,0,SEEK_END );

	return resultado;
}

bool LockFile:: is_open()
{
	return (this->fd > 0);
}

int LockFile :: getFileDescriptor()
{
	return this->fd;
}

void LockFile::abrir()
{
	if ( this->fd <= 0)
		this->fd = open ( this->nombre.c_str(), O_CREAT | O_RDWR, 0777 );
}

void LockFile::cerrar()
{
	close ( this->fd );
}

LockFile :: ~LockFile () {
	liberarLock();
	cerrar();
}
